package com.zyz.N_反射机制.基本应用.获取运行时类的完整结构;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * @author: vick
 * @Date: 2025/4/14
 * @Description:
 * @version: 1.0
 */
public class Test2 {
    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> clazz = Class.forName("com.vick.N_反射机制.基本应用.获取运行时类的完整结构.User2");

        //获取到运行时类本身及其所有的父类中声明为public权限的方法
        /*Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }*/

        //获取当前运行时类中声明的所有方法
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            //1. 获取方法声明的注解
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                System.out.println(annotation);
            }

            //2.获取权限修饰符
            int modifiers = method.getModifiers();
            System.out.print(Modifier.toString(modifiers) + "\t");

            //3. 获取返回值类型
            String name = method.getReturnType().getName();
            System.out.print(name + "\t");

            //4. 获取方法名
            String name1 = method.getName();
            System.out.print(name1 + "\t");

            //5. 形参列表
            System.out.print("(");
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes != null && parameterTypes.length != 0) {
                for (int i = 0; i < parameterTypes.length; i++) {
                    if (i == parameterTypes.length - 1) {
                        System.out.print(parameterTypes[i].getName());
                        break;
                    }
                    System.out.print(parameterTypes[i].getName() + ",");
                }
            }
            System.out.print(")");

            //6. 抛出的异常
            Class<?>[] exceptionTypes = method.getExceptionTypes();
            if (exceptionTypes.length > 0) {
                System.out.print(" throws ");
                for (int i = 0; i < exceptionTypes.length; i++) {
                    if (i == exceptionTypes.length - 1) {
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }
                    System.out.print(exceptionTypes[i].getName() + ",");
                }
            }

            System.out.println();
        }
    }
}
